import { useState, useCallback, useEffect } from "react";
import { Button, Checkbox, Form, type FormProps, Input, message } from "antd";
import type { CheckboxProps } from "antd";
import { useNavigate } from "react-router-dom";
import { Link } from "react-router-dom";
import { request } from "../common/request";
import { urls } from "../common/urls";
import { encryptStr } from "../util/index";
import "./index.less";

type FieldType = {
  mobile?: string;
  password?: string;
  newPassword?: string;
  code?: string;
};

const typeText: any = {
  login: '登录',
  register: '注册',
  forget: '修改'

};


function Login() {
  const [type, setType] = useState("login");
  const [checked, setChecked] = useState(false);
  const navigate = useNavigate();
  const [messageApi, contextHolder] = message.useMessage();
  const [loading, setLoading] = useState(false);


  const getProfileList = (info: any) => {
    request({
      method: "post",
      data: {
        method: urls.profileList,
        session_key: info.session_key
      },
    }).then((res: any) => {
      const userInfo = {
        ...info,
        ...res.data,
        session_key: info.session_key,
      }
      localStorage.setItem("userInfo", JSON.stringify(userInfo));
      setTimeout(() => {
        setLoading(false);
        window.tw.ipcRenderer.send('login-success');
      }, 500);
    });
  };

  useEffect(() => {
    try {
      window.tw.ipcRenderer.on('login-success-callback', () => {
        navigate("/chat");
      })
    } catch (error) {

    }
  }, [])

  const onFinish: FormProps<FieldType>["onFinish"] = useCallback(
    (values: any) => {
      if (!checked && type !== "forget") {
        messageApi.open({
          type: "warning",
          content: "请勾选同意",
        });
        return;
      }
      const { mobile, password } = values;
      switch (type) {
        case "register":
          request({
            method: "post",
            data: {
              method: urls.register,
              mobile: encryptStr(encodeURI(mobile)), // 有点问题解密
              password,
            },
          }).then(() => {
            setType("login");
          });
          break;
        case "login":
          setLoading(true);
          request({
            method: "post",
            data: {
              method: urls.login,
              mobile: encryptStr(mobile),
              password,
            },
          }).then((res: any) => {
            getProfileList(res.data);
          });
          break;
        case "forget":
          request({
            method: "post",
            data: {
              method: urls.forgetPwd,
              mobile: encryptStr(mobile), // 有点问题解密
              password,
            },
          }).then(() => {
            setType("login");
          });
          break;
      }
    },
    [checked, type, messageApi, navigate]
  );

  const onFinishFailed: FormProps<FieldType>["onFinishFailed"] = (
    errorInfo
  ) => {
    console.log("Failed:", errorInfo);
  };

  const handleChange: CheckboxProps["onChange"] = (e) => {
    const { checked } = e.target;
    setChecked(checked);
  };

  return (
    <>
      {contextHolder}
      <div className="login-container">
        <div className="login-logo"></div>
        <div className="login-content">欢迎使用Twitter</div>
        <Form
          name="basic"
          className="login-form"
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item<FieldType>
            name="mobile"
            rules={[{ required: true, message: "请输入手机号" }]}
          >
            <Input className="login-form-input" placeholder="请输入手机号" />
          </Form.Item>
          {type === "login" && (
            <Form.Item<FieldType>
              name="password"
              rules={[{ required: true, message: "请输入密码" }]}
            >
              <Input.Password
                className="login-form-input"
                placeholder="请输入密码"
              />
            </Form.Item>
          )}
          {type === "forget" && (
            <>
              <Form.Item<FieldType>
                name="password"
                rules={[{ required: true, message: "请输入新密码" }]}
              >
                <Input.Password
                  className="login-form-input"
                  placeholder="请输入新密码"
                />
              </Form.Item>
              <Form.Item<FieldType>
                name="newPassword"
                rules={[{ required: true, message: "请确认新密码" }]}
              >
                <Input.Password
                  className="login-form-input"
                  placeholder="请确认新密码"
                />
              </Form.Item>
            </>
          )}
          {type === "register" && (
            <>
              <Form.Item<FieldType>
                name="password"
                rules={[{ required: true, message: "请输入密码" }]}
              >
                <Input.Password
                  className="login-form-input"
                  placeholder="请输入密码"
                />
              </Form.Item>
              <Form.Item<FieldType> name="code">
                <Input
                  className="login-form-input"
                  placeholder="请输入邀请码"
                />
              </Form.Item>
            </>
          )}

          <Form.Item>
            <Button className="login-form-btn" type="primary" htmlType="submit">
              {loading ? '登录中...' : typeText[type]}
            </Button>
          </Form.Item>
        </Form>
        {type === "login" && (
          <div className="login-operate">
            <div
              className="login-operate-item"
              onClick={() => setType("forget")}
            >
              忘记密码
            </div>
            <div
              className="login-operate-item"
              onClick={() => setType("register")}
            >
              注册账号
            </div>
          </div>
        )}
        {type !== "login" && (
          <div className="login-operate">
            <div
              className="login-operate-item"
              onClick={() => setType("login")}
            >
              立即登录
            </div>
          </div>
        )}
        {type !== "forget" && (
          <Checkbox className="login-agree" onChange={handleChange}>
            我已阅读并同意
            <Link to="/">《用户协议》</Link>和<Link to="/">《隐私政策》</Link>
          </Checkbox>
        )}
      </div>
    </>
  );
}

export default Login;
